<template>
    <el-dialog width="30%" title="合同上传" :visible.sync="innerVisible" @close="handleClose">
        <el-form :model="form" ref="form" :rules="rules">
            <el-form-item label="供给方名称" :label-width="formLabelWidth" prop="supplierId">
                <el-select @change="changeVal" v-model="form.supplierId" placeholder="请选择">
                    <el-option :label="item.nickName" :value="item.id" v-for="item in userData" :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="合同文件" ref="headimgUpload" :label-width="formLabelWidth" prop="contractUrl">
                <el-upload class="upload-demo" :limit="1" :action="fileUploadUrl" :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload" :on-remove="handleRemove" accept=".pdf" :on-error="handleError"
                    :file-list="fileList">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div class="el-upload__tip" slot="tip">上传文件不超过10M</div>
                </el-upload>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="innerVisible = false">取 消</el-button>
            <el-button type="primary" :loading="loading" @click="handleSure">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import { contactsListUpload, resourceContract } from "@/request/api/resource"
export default {
    data() {
        return {
            form: {
                id: "", //
                supplierId: '',//供给方id
                supplierName: "", //供给方名称
                contractName: "",//合同名称
                contractUrl: "" //合同附件URL
            },
            loading: false,
            innerVisible: false,
            formLabelWidth: '100px',
            fileUploadUrl: '/dev-api/file/upload/uploadNotQR',
            rules: {
                supplierName: [
                    { required: true, message: '请输入供给方名称', trigger: 'blur' },
                ],
                contractUrl: [
                    { required: true, message: '请上传合同附件', trigger: 'change' },
                ],
            },
            fileList: [],
            userData: [],
            supplyDemand: '',//类型（0需求 1供应）
        }
    },
    methods: {
        open(id, supplyDemand) {
            this.supplyDemand = supplyDemand
            this.innerVisible = true
            this.form.id = id
            this.fileList = []
            this.getResoure()
        },
        // 获取联系人列表
        getResoure() {
            let params = {
                resourceId: this.form.id
            }
            contactsListUpload(params).then(res => {
                this.loading = false
                if (res.data.code === 200) {
                    this.userData = res.data.result.items
                }
            })
        },
        // 上传文件成功
        handleAvatarSuccess(response, file, fileList) {
            this.form.contractName = file.name
            this.form.contractUrl = file.response.message
            this.$refs.headimgUpload.clearValidate(); // 关闭校验
        },
        // 上传文件失败
        handleError(err) {
            let errInfo = JSON.parse(err["message"]);
            this.$message.error(`文件上传失败，原因：${errInfo.message}`);
        },
        //删除上传的文件
        handleRemove() {
            this.form.contractName = ''
            this.form.contractUrl = ''
        },
        // 限制上传的类型
        beforeAvatarUpload(file) {
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                this.$message.error("上传图片大小不能超过 10M!");
                return false;
            }
            var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
            const extension = testmsg === "pdf";
            if (!extension) {
                this.$message({
                    message: "上传文件只能是 pdf 格式!",
                    type: "error",
                });
                return false;
            }
        },
        // 确认
        handleSure() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let text = ''
                    if (this.supplyDemand == '0') {//需求
                        text = '您是否确认上传合同，与' + this.form.supplierName + '达成合作？（合同一经上传无法更改，请谨慎上传!）'
                    } else if (this.supplyDemand == '1') {//供应
                        text = '您是否确认上传合同，授权' + this.form.supplierName + '使用资源？（合同一经上传无法更改，请谨慎上传!）'
                    }
                    this.$confirm(text, "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }).then(() => {
                        this.loading = true
                        let params = {
                            id: this.form.id,
                            contractDtos: [
                                {
                                    accessoryName: this.form.contractName, //合同名称
                                    companyName: this.form.supplierName, //供给方公司名称
                                    accessoryUrl: this.form.contractUrl, //url
                                    supplyId: this.form.supplierId //供给方id
                                }
                            ]
                        }
                        resourceContract(params).then((res) => {
                            this.loading = false
                            if (res.data.code === 200) {
                                this.$message({
                                    message: res.data.message,
                                    type: "success",
                                });
                                this.innerVisible = false
                                // this.getDetail(this.form.id)
                            } else {
                                this.$message.error(res.data.message);
                            }
                        });
                    });

                }
            })
        },
        handleClose() {
            this.$emit('getResoure')
            this.$refs.form.resetFields();
        },
        changeVal(val) {
            console.log(val)
            this.userData.forEach(item => {
                if (val == item.id) {
                    this.form.supplierName = item.nickName
                }
            })
        }
    }
}
</script>
<style lang="less" scoped></style>

